<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class ServiceOrder extends Backend
{

    /**
     * ServiceOrder模型对象
     * @var \app\admin\model\ServiceOrder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\ServiceOrder;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['service','user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','order_no','status','createtime']);
                $row->visible(['service']);
				$row->getRelation('service')->visible(['service_name']);
				$row->visible(['user']);
				$row->getRelation('user')->visible(['nickname','mobile']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    //修改
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }

        //为了避免订单中资金重复发放，建立标识
        $is_money = Db::name("user_money_log")
        ->where("order_id = " . $row["id"])
        ->find();
        $money_readonly = 0;
        if($is_money){
            $money_readonly = 1;
        }

        if (false === $this->request->isPost()) {
            $row["service_name"] = Db::name("service")
            ->where("id = " . $row["service_id"])
            ->find()["service_name"] ?? "";

            $row["branch_office_name"] = Db::name("user")
            ->where("id = " . $row["branch_office_uid"])
            ->find()["nickname"] ?? "";

            $row["agent_name"] = Db::name("user")
            ->where("id = " . $row["agent_uid"])
            ->find()["nickname"] ?? "";

            $row["sale_name"] = Db::name("user")
            ->where("id = " . $row["sale_uid"])
            ->find()["nickname"] ?? "";

            $this->view->assign('row', $row);
            $this->view->assign('money_readonly', $money_readonly);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');

        if(!isset($params["status"])){
            $params["status"] = 2;
        }

        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        //按照填写的角色提成比例，计算金额
        if($params["branch_office_rate"] > 0 && $money_readonly == 0 && $params["order_money"] > 0){
            //查询当前用户余额
            $branch_office_balance = Db::name("user")->where("id = " . $row["branch_office_uid"])->find()["money"];
            $params["branch_office_money"] = bcdiv(bcmul($params["order_money"], $params["branch_office_rate"], 2), 100, 2);
        }

        if($params["agent_rate"] > 0 && $money_readonly == 0 && $params["order_money"] > 0){
            $agent_balance = Db::name("user")->where("id = " . $row["agent_uid"])->find()["money"];
            $params["agent_money"] = bcdiv(bcmul($params["order_money"], $params["agent_rate"], 2), 100, 2);
        }

        if($params["sale_rate"] > 0 && $money_readonly == 0 && $params["order_money"] > 0){
            $sale_balance = Db::name("user")->where("id = " . $row["sale_uid"])->find()["money"];
            $params["sale_money"] = bcdiv(bcmul($params["order_money"], $params["sale_rate"], 2), 100, 2);
        }

        //判断当前状态是否结束，是否可以发放金额  0咨询中  1已成交   2已结束
        if($params["status"] == 2 && $money_readonly == 0 && $params["order_money"] > 0){
            if($params["branch_office_money"] > 0){
                Db::name("user")->where("id = " . $row["branch_office_uid"])->setInc("money", $params["branch_office_money"]);
                Db::name("user_money_log")
                ->insert([
                    "user_id" => $row["branch_office_uid"],
                    "money" => $params["branch_office_money"],
                    "before" => $branch_office_balance,
                    "after" => bcadd($branch_office_balance, $params["branch_office_money"], 2),
                    "memo" => "订单发放分公司提成",
                    "order_id" => $params["id"],
                    "createtime" => time()
                ]);
            }

            if($params["agent_money"] > 0){
                Db::name("user")->where("id = " . $row["agent_uid"])->setInc("money", $params["agent_money"]);
                Db::name("user_money_log")
                ->insert([
                    "user_id" => $row["agent_uid"],
                    "money" => $params["agent_money"],
                    "before" => $agent_balance,
                    "after" => bcadd($agent_balance, $params["agent_money"], 2),
                    "memo" => "订单发放代理商提成",
                    "order_id" => $params["id"],
                    "createtime" => time()
                ]);
            }

            if($params["sale_money"] > 0){
                Db::name("user")->where("id = " . $row["sale_uid"])->setInc("money", $params["sale_money"]);
                Db::name("user_money_log")
                ->insert([
                    "user_id" => $row["sale_uid"],
                    "money" => $params["sale_money"],
                    "before" => $sale_balance,
                    "after" => bcadd($sale_balance, $params["sale_money"], 2),
                    "memo" => "订单发放销售提成",
                    "order_id" => $params["id"],
                    "createtime" => time()
                ]);
            }
        }
        
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);

            //同步修改对应服务申请中的状态
            Db::name("service_apply")
            ->where("id = " . $row["apply_id"])
            ->update(["status" => $params["status"]]);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    //导出数据
    public function export()
    {
        set_time_limit(0);//设置时间限制
        $ids = $this->request->post('ids'); //获取数据的所有id

        //导出的字段
        $field = [
            'order_no',
            'apply_name',
            'user>nickname',
            'status',
            'order_money',
            'branch>nickname',
            'branch_office_rate',
            'branch_office_money',
            'agent>nickname',
            'agent_rate',
            'schedule_json',
            'agent_money',
            'sale>nickname',
            'sale_rate',
            'sale_money',
            'createtime',
            'updatetime'
        ];
        //连表数据需要显示的字段，user>mobile表示为：user表下的mobile字段
        $fieldComment = [
            'user>nickname' => '用户昵称',
            'branch>nickname' => '分公司昵称',
            'agent>nickname' => '代理商昵称',
            'sale>nickname' => '销售昵称',
        ];
        $fields = $this->getField($field, "service_order");

        $objPHPExcel = new Spreadsheet();
        $firstChar = 65;
        $tempChar = '';
        $tempCharNum = '';
        foreach ($fields as $key => &$field) {
            //当列超出 A-Z时，为：AA-AZ,BA-BZ，以此类推
            if ($firstChar > 90) {
                $firstChar = 65; //当超出 Z 时，重新跳到 A 开始

                if ($tempChar == '') {
                    $tempCharNum = 65;//当超出 Z 时，从 A 开始时需要加上 A-Z
                } else {
                    $tempCharNum += 1;
                }
                $tempChar = chr($tempCharNum);
            }
            $column = chr($firstChar);
            $firstChar++;

            $char = $tempChar . $column; //哪一列

            //处理连表的导出字段
            if (is_numeric($field)) {
                $field = [
                    'field' => $key,
                    'comment' => $fieldComment[$key],
                    'type' => 'varchar',
                    'chose' => [],
                ];
            }
            $field['char'] = $char;//记录哪一列，数据循环时可直接取用
            //设置表头
            $objPHPExcel->getActiveSheet()->setCellValue($char . '1', $field['comment']);
            //改变长度
            $objPHPExcel->getActiveSheet()->getColumnDimension($char)->setWidth(30);
        }


        //查询数据
        $wheres = [
        
        ];
        if ($ids != 'all' && !empty($ids)) {
            $wheres['service_order.id'] = ['in', $ids];
        }
        $list = $this->model
            ->with([
                'user',
                'branch',
                'agent',
                'sale'
                ])
            ->where($wheres)
            ->select();

        //输出表格
        foreach ($list as $key => &$val) {
            $val = $val->toArray();
            $i = $key + 2;//表格是从2开始的,第1行为表头
            foreach ($fields as &$field) {
                $data = $val[$field['field']] ?? '';
                
                if($field['field'] == "schedule_json"){
                    $data = substr($val["schedule_json"], 1, bcsub(strlen($val["schedule_json"]), 2));
                }
                //连表显示的字段
                if (strpos($field['field'], '>') !== false) {
                    $fieldArr = explode('>', $field['field']);
                    $data = $val[$fieldArr[0]][$fieldArr[1]];
                }
                //转换为时间格式
                if (is_numeric($data) && mb_strlen($data) == 10) {
                    $data = date('Y-m-d H:i:s', $data);
                }
                //将选择项转换成对应的值
                if (!empty($field['chose'])) {
                    $data = $field['chose'][$data];
                }
                //将char和varchar数据类型的单元格设置为文本类型，以防出现科学计数法
                if (strpos($field['type'], 'char') !== false) {
                    $objPHPExcel->getActiveSheet()->setCellValueExplicit($field['char'] . $i, $data, 's');
                } else {
                    $objPHPExcel->getActiveSheet()->setCellValue($field['char'] . $i, $data);
                }
            }
        }

        $outputFileName = date("YmdHis") . '导出.xls';

        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="' . $outputFileName . '"');
        header("Content-Transfer-Encoding: binary");
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Xlsx');
        $objWriter->save('php://output');
        exit;
    }


}
